package com.woniuxy.shop.service;

import java.util.List;

import com.woniuxy.shop.dao.CateGoryDao;
import com.woniuxy.shop.dao.GoodsDao;
import com.woniuxy.shop.entity.CateGory;
import com.woniuxy.shop.exception.CannotDeleteCateGoryException;
import com.woniuxy.shop.exception.DaoException;
import com.woniuxy.shop.exception.NotExistThisCateGoryException;
import com.woniuxy.shop.exception.SameCateGoryException;
import com.woniuxy.shop.exception.ServiceException;

/**
 * @author 作者： version 创建时间： 类说明：
 */
public class CateGoryService {
	CateGoryDao cgd = new CateGoryDao();

	public void add(CateGory cg) {
		// 判断类别是否存在
		try {
			if (cgd.getCateGoryByName(cg.getName()) != null) {
				throw new SameCateGoryException("该类别已存在");
			}
			cgd.add(cg);
		} catch (DaoException e) {
			throw new ServiceException("sql执行异常", e);
		}
	}

	// 更改指定id的类别的状态
	public void update(CateGory cg) {
		try {
			CateGory temp = cgd.getCateGoryByName(cg.getName());
			if (temp!=null&&!temp.getName().equals(cg.getName())) {
				throw new SameCateGoryException(cg.getName() + "类别已存在");
			}
			cgd.update(cg);
		} catch (DaoException e) {
			throw new ServiceException("sql执行异常", e);
		}
	}

	public void updateName(String oldName, String newName) {
		try {
			CateGory cg = cgd.getCateGoryByName(oldName);
			if (cg == null) {
				throw new NotExistThisCateGoryException("该类别不存在：" + oldName);
			}
			cgd.updateName(cg.getId(), newName);
		} catch (DaoException e) {
			throw new ServiceException("sql执行异常", e);
		}
	}

	/*
	 * 查询所有类别信息
	 */
	public List<CateGory> getCateGory() {
		List<CateGory> categories = cgd.getAllCateGory();
		return categories;
	}

	/**
	 * 根据指定ID查询类别信息
	 * 
	 * @param id
	 * @return
	 */
	public CateGory getCateGoryById(int id) {
		return cgd.getCateGoryById(id);
	}

	public void delete(int id) {
		GoodsDao gd = new GoodsDao();
		if (gd.queryGoodsByCateGoryId(id).size() != 0) {
			throw new CannotDeleteCateGoryException("该类别已有商品，不能被删除");
		}
		cgd.delete(id);
	}
}
